
import { updateProductCustomers } from "@/services/product/product_api";
import {listCustomer} from "@/services/customer/custom_api";
import {
  ModalForm,
  ProForm,
  ProFormDigit,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from "@ant-design/pro-components";
import dayjs from "dayjs";
import { message } from "antd";
import React, { useState, useEffect } from "react";
import { useIntl } from "umi";


interface CreateModalProps {
  visible: boolean;
  values?: ProductCustomerVo;
  onCancel: () => void;
  onSuccess: () => void;
}


const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};
const AddFormProduct: React.FC<CreateModalProps> = ({
  visible,
  values,
  onCancel,
  onSuccess,
}) => {
  const [form] = ProForm.useForm<ProductCustomerVo>();
  const intl = useIntl();

  // const [updateStatus, setUpdateStatus] = useState<boolean>(false);
  const [editStatus, setEditStatus] = useState<boolean>(false);

  const [initCustomers, setInitCustomers] = useState<[]>([]);
  const [loading, setLoading] = useState(false);
  const [customerMap, setCustomerMap] = useState<Map<string, CustomerVo>>(new Map());
  const [selectCustomers,setSelectCustomers] = useState<CustomerVo[]>([]);


  useEffect(() => {
    const initForm = async() => {
      setLoading(true);
      try {
        await initActivateCustomers();
        if (visible) {
          if (values) {
            // console.log("rule:" + JSON.stringify(values));
            setEditStatus(true);
          }
          let selectValues:string[] =[];
          const selectedDt: CustomerVo[] = [];
          if (values?.customers) {
            values?.customers.map(item => {
              selectValues.push(item.customerCode);
              selectedDt.push({
                id: item.id,
                customerName: item.customerName,
                customerCode: item.customerCode,
                customerStatus: item.customerStatus,
              });
            })

            setSelectCustomers(selectedDt);
          }         
          // values?.products = selectValues;
          form.setFieldsValue(values || {});
          form.setFieldsValue({customersSelect:selectValues})
        }
      } finally {
        setLoading(false);
      }
    };
    initForm();
  }, [visible, values]);


  const initActivateCustomers = async () => {
      try {
        // Basic_Rate  Extras_Fee
        // Replace with your actual API endpoint
        const response = await listCustomer({status:0});
        if (response.code != 0) {
          if (!response.msg) {
            throw new Error(intl.formatMessage({ id: "request.error.create" }));
          } else {
            message.error(response.msg);
          }
        }     
        const options = response.data.map(item => ({
          label: item.customerName,  // Display text
          value: item.customerCode   // Actual value stored in form
        }));
  
        setInitCustomers(options);
        const convertedMap = new Map(response.data.map(item => [item.customerCode, item]));
        setCustomerMap(convertedMap);
        // console.info("init basefee:"+JSON.stringify(options));
        // setBasefeeRules( response.data);
      } catch (error) {
        console.error('Failed to fetch fee options:', error);
        // You might want to set some default options or show an error message
        
      }
    }

  const handleSubmit = async (formValues: ProductCustomerVo) => {
    //  console.log("customer1:" + JSON.stringify(values));

    if (values?.prId) {    

      try {
        // API调用逻辑
        const response = await updateProductCustomers(values?.prId, selectCustomers);

        if (response.code != 0) {
          if (!response.msg) {
            throw new Error(
              intl.formatMessage({ id: "request.error.operating" })
            );
          } else {
            // throw new Error(response.msg);
            message.error(response.msg);
            return false;
          }
        }
        message.success(intl.formatMessage({ id: "request.success.operating" }));
        onSuccess();
        form.resetFields();
        return true;
      } catch (error) {
        message.error(intl.formatMessage({ id: "request.error.retry" }));
        return false;
      }
    }
  };


  const closeModel = () => {
    form.resetFields;
    // setCalculationRuleValue(undefined);
    onCancel();
  }


  const onSelectChange = (selectValues) => {
    console.log("select:" + selectValues);
    const selectedPrds: CustomerVo[] = [];

    selectValues.forEach(code => {
      const cust = customerMap.get(code);
      if (cust) {
        selectedPrds.push(cust);
      }
    });
    setSelectCustomers(selectedPrds);
  }



  return (
    <ModalForm<ProductCustomerVo>
      title={
        values?.prId
          ? intl.formatMessage({ id: "pages.edit" })
          : intl.formatMessage({ id: "pages.create" })
      }
      width="60%"
      style={{ height: '70%' }} // 设置整体高度为79%
      loading={loading}
      form={form}
      open={visible}
      onOpenChange={(visible) => !visible && closeModel()}
      onFinish={handleSubmit}
      // onValuesChange={handleValuesChange} // 监听值变化
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
      }}
      submitter={{
        searchConfig: {
          submitText: intl.formatMessage({ id: "pages.button.submit" }),
          resetText: intl.formatMessage({ id: "pages.button.cancel" }),
        },
      }}
      layout="horizontal"
      {...formItemLayout}
    >
      {/* 单列布局 - 移除了所有 ProForm.Group */}
      {/* <ProForm.Group></ProForm.Group>  */}
      {/* 单列布局 */}
      <ProFormText
        name="prName"
        disabled={editStatus}
        // readonly = {editStatus}
        colProps={{ md: 12, xl: 8 }}
        label={intl.formatMessage({
          id: "pages.addForm.customer.customerName",
          defaultMessage: "Customer Name",
        })}  
      />

      <ProFormText
        name="prCode"
        disabled={editStatus}
        // readonly = {editStatus}
        colProps={{ md: 12, xl: 8 }}
        label={intl.formatMessage({
          id: "pages.addForm.customer.customerName",
          defaultMessage: "Customer Code",
        })}
      />
      <ProFormRadio.Group
        name="prStatus"
        label={intl.formatMessage({
          id: "pages.status",
          defaultMessage: "Status",
        })}
        // disabled={editStatus}
        readonly={editStatus}
        style={{ width: "50%" }}
        // rules={[{ required: true }]}
        initialValue={1}
        options={[
          {
            label: intl.formatMessage({ id: "pages.status.enabled" }),
            value: 0,
            style: {
              color: '#52c41a', // 启用状态颜色 - 绿色
              fontWeight: 'bold'
            }
          },
          {
            label: intl.formatMessage({ id: "pages.status.disabled" }),
            value: 1,
            style: {
              color: '#ff4d4f', // 禁用状态颜色 - 红色
              fontWeight: 'bold'
            }
          },
        ]}
      />


      <ProFormSelect
        name= "customersSelect"  // Simplified name since we're not in a Form.List
        label={intl.formatMessage({ id: 'pages.customer.select.label' })}
        placeholder={intl.formatMessage({ id: 'pages.customer.select.placeholder' })}
        mode="multiple" 
        colProps={{ span: 16 }} // 占据一半宽度
        // rules={[{ required: true, message: "请选择收费规则" }]}
        fieldProps={{
          onChange: (values) => {
            onSelectChange(values);
          },
        }}
        options={initCustomers}
      />
    </ModalForm>
  );
};

export default AddFormProduct;
